package com.enjoyor.health.HGPT.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoyor.health.HGPT.core.config.ParamConfig;
import com.enjoyor.health.HGPT.core.dto.TestQuestionDto;
import com.enjoyor.health.HGPT.core.dto.TestQuestionResultDto;
import com.enjoyor.health.HGPT.core.entity.*;
import com.enjoyor.health.HGPT.core.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Zhu Min
 * @date 2023/10/20 13:14
 */
@Slf4j
@Service
public class BizSelfTestService {

    @Autowired
    private ISelftestContentService selftestContentService;
    @Autowired
    private ISelftestQuestionService selftestQuestionService;
    @Autowired
    private ISelftestUserrecordService selftestUserrecordService;
    @Autowired
    private IUserInfoMiniappService userInfoMiniappService;
    @Autowired
    private ISelftestRecordService selftestRecordService;
    @Autowired
    private ParamConfig paramConfig;


    public List<SelftestContent> getSelftestContent(String selftestId){
        return selftestContentService.getSelftestContentBySelftestId(selftestId);
    }

    public JSONObject getDBTestQuestions(String selftestId, String openId){
        LocalDateTime now = LocalDateTime.now();
        String recordId = IdUtil.simpleUUID();
        String type = "";

        List<TestQuestionDto> testQuestionDtoList = selftestQuestionService.getTestQuestionDtoListById(selftestId);
        JSONObject questions = new JSONObject();
        type = testQuestionDtoList.get(0).getTitleEn();
        Map<String, List<TestQuestionDto>> questionMap =  testQuestionDtoList.stream()
                .collect(Collectors.groupingBy(TestQuestionDto::getQuestion));
        questionMap.forEach((k,v)->{
            if (v.size() >0){
                JSONObject question = new JSONObject();
                question.put("question", v.get(0).getQuestion());
                question.put("number", v.get(0).getSn());
                question.put("answers", new JSONArray());
                JSONArray array = new JSONArray();
                for (TestQuestionDto testQuestionDto : v) {
                    JSONObject answer = new JSONObject();
                    answer.put("value", testQuestionDto.getOptions());
                    answer.put("name", testQuestionDto.getName());
                    answer.put("checked", false);
                    answer.put("score", testQuestionDto.getScore());
                    array.add(answer);
                }
                question.put("answers", array);
                questions.put(v.get(0).getSn() + "", question);
            }
        });

        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        String userId = openId;
        if (userInfoMiniapp != null){
            userId = userInfoMiniapp.getUserId();
        }else {
            log.info("get_DB_testQuestions-无userid，用openid代替 {}", openId);
        }

        SelftestUserrecord selftestUserrecord = new SelftestUserrecord();
        selftestUserrecord.setId(recordId);
        selftestUserrecord.setSelftestId(selftestId);
        selftestUserrecord.setUserId(userId);
        selftestUserrecord.setTestTime(now);
        selftestUserrecordService.save(selftestUserrecord);
        //
        JSONObject result = new JSONObject();
        result.put("testing", questions.values());
        result.put("questionCount", questions.values().size());
        result.put("recordId", recordId);
        result.put("type", type);
        return result;
    }

    public JSONObject getDBTestQuestionsScore(TestQuestionResultDto testQuestionResultDto){
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(testQuestionResultDto.getOpenId());
        String userId = userInfoMiniapp==null?testQuestionResultDto.getOpenId() : userInfoMiniapp.getUserId();
        for (TestQuestionResultDto.Testing testing : testQuestionResultDto.getTesting()) {
            for (TestQuestionResultDto.Testing.Answer answer : testing.getAnswers()) {
                if (answer.isChecked()){
                    String uuid = IdUtil.simpleUUID();
                    SelftestRecord record = new SelftestRecord();
                    record.setId(uuid);
                    record.setUserId(userId);
                    record.setRecordId(testQuestionResultDto.getRecordId());
                    record.setSelftestId(testQuestionResultDto.getSelftestId());
                    record.setQuestionNumber(testing.getNumber());
                    record.setAbcd(answer.getValue());
                    record.setTestTime(LocalDateTime.now());
                    record.setScore(answer.getScore());
                    selftestRecordService.insertSelftestRecord(record);
                }
            }
        }
        //
        int score = selftestRecordService.sumScore(testQuestionResultDto.getRecordId());
        List<SelftestContent> selftestContentList = selftestContentService.getSelftestContentByScore(score, testQuestionResultDto.getSelftestId());
        JSONObject result = new JSONObject();
        if (selftestContentList.size()>0){
            result.put("score", score);
            result.put("resultConcise", selftestContentList.get(0).getResultAbb());
            JSONArray array = new JSONArray();
            array.add(selftestContentList.get(0).getResult());
            array.add(selftestContentList.get(0).getContent());
            result.put("resultDetailed", array);
            result.put("type", selftestContentList.get(0).getTitleEn());
        }
        return result;
    }

    public JSONArray getDBHealthTable(){
        JSONArray result = new JSONArray();
        List<SelftestContent> selftestContentList = selftestContentService.getSelftestContentList();
        for (SelftestContent selftestContent : selftestContentList) {
            JSONObject content = new JSONObject();
            content.put("id", selftestContent.getId());
            content.put("abstrct", selftestContent.getAbstrct());
            content.put("title", selftestContent.getTitle());
            content.put("coverUrl", StringUtils.isNotBlank(selftestContent.getCoverUrl())? paramConfig.getReportUrl() + selftestContent.getCoverUrl() : null);
            result.add(content);
        }
        return result;
    }

    public Page<SelftestContent> getSelfTestContentPage(String title, String state, int page, int size){
        return selftestContentService.getSelfTestContePage(title, state, page, size);
    }

    public JSONObject getById(String id){
        List<SelftestContent> selftestContentList = selftestContentService.getSelfTestContentById(id);
        List<SelftestQuestion> selftestQuestionList = selftestQuestionService.getSelftestQuestionById(id);




        //TODO
        return null;

    }

}
